<template>
  <div class="app-container">
    <!-- 调度方案列表区域 -->
    <el-card class="schedule-list-card">
      <template #header>
        <div class="card-header">
          <span>调度方案列表</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAddToLibrary">
              <el-icon>
                <Plus />
              </el-icon>添加方案库
            </el-button>
            <el-button type="success" @click="handleCopyScheme">
              <el-icon>
                <CopyDocument />
              </el-icon>复制方案
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="schemeList" border v-loading="loading" class="mt-2">
        <el-table-column prop="expDate" label="日期" width="120" align="center" />
        <el-table-column prop="title" label="调度方案简述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="supplyTotal" label="供水量(M³)" width="120" align="center">
          <template #default="{ row }">
            {{ formatNumber(row.supplyTotal) }}
          </template>
        </el-table-column>
        <el-table-column prop="pressureAvg" label="平均压力(MPa)" width="120" align="center">
          <template #default="{ row }">
            {{ row.pressureAvg }}
          </template>
        </el-table-column>
        <el-table-column prop="ratingStar" label="评分" width="100" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.ratingStar" disabled show-score text-color="#ff9900" score-template="{value} 星" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" type="primary" @click="handleCopy(row)">复制</el-button>
            <el-button size="small" type="success" @click="handleSave(row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 调度方案详情区域 -->
    <el-card class="schedule-detail-card mt-2" v-if="currentScheme">
      <template #header>
        <div class="card-header">
          <span>调度方案详情-{{ currentScheme.expDate }}</span>
          <div class="detail-buttons">
            <el-button type="primary" @click="handleSaveToLibrary">保存到方案库</el-button>
            <el-button type="success" @click="handleCopyToFuture">复制到未来</el-button>
            <el-button @click="currentScheme = null">
              <el-icon>
                <Close />
              </el-icon>关闭
            </el-button>
          </div>
        </div>
      </template>

      <div class="detail-content">
        <!-- 基本信息 -->
        <div class="basic-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>日期：</label>
                <span>{{ currentScheme.expDate }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>供水量：</label>
                <span>{{ formatNumber(currentScheme.supplyTotal) }} 吨</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>平均压力：</label>
                <span>{{ currentScheme.pressureAvg }} MPa</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-1">
            <el-col :span="8">
              <div class="info-item">
                <label>调度评分：</label>
                <span>
                  <el-rate v-model="currentScheme.ratingStar" disabled show-score text-color="#ff9900"
                    score-template="{value} 星" />
                </span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>方案状态：</label>
                <el-tag :type="currentScheme.inLibrary === 1 ? 'success' : 'info'">
                  {{ currentScheme.inLibrary === 1 ? '已入库' : '未入库' }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 机泵运行记录表格 -->
        <el-card class="mt-2">
          <template #header>
            <span>机泵运行记录</span>
          </template>
          <el-table :data="currentScheme.records" border
            v-if="currentScheme.records && currentScheme.records.length > 0">
            <el-table-column prop="timeStart" label="开始时间" align="center" />
            <el-table-column prop="timeEnd" label="结束时间" align="center" />
            <el-table-column prop="flowM3h" label="流量(m³/h)" align="center" />
            <el-table-column prop="pressureMpa" label="压力(MPa)" align="center" />
            <el-table-column prop="powerKw" label="功率(kW)" align="center" />
            <el-table-column label="机泵状态" align="center">
              <template #default="{ row }">
                <div v-if="row.pumpStatusJson" class="pump-status">
                  <div v-for="pump in parsePumpStatus(row.pumpStatusJson)" :key="pump.name" class="pump-status-item">
                    <span class="pump-name">{{ pump.name }}：</span>
                    <el-tag :type="getPumpStatusType(pump.state)" size="small">
                      {{ pump.state }}
                    </el-tag>
                  </div>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="no-data">暂无运行记录数据</div>
        </el-card>

        <!-- 效果数据图表 -->
        <el-row :gutter="20" class="mt-2">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>流量趋势</span>
                <span class="unit">单位：m³/h</span>
              </template>
              <ChartComponent :option="flowChartOption" :style="{ height: '300px' }" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>压力变化</span>
                <span class="unit">单位：MPa</span>
              </template>
              <ChartComponent :option="pressureChartOption" :style="{ height: '300px' }" />
            </el-card>
          </el-col>
        </el-row>

        <!-- 调度效果分析图表 -->
        <el-card class="mt-2">
          <template #header>
            <span>调度效果分析</span>
          </template>
          <ChartComponent :option="effectAnalysisChartOption" :style="{ height: '400px' }" />
        </el-card>
      </div>
    </el-card>

    <!-- 新增/复制方案对话框 -->
    <el-dialog v-model="schemeDialog.visible" :title="schemeDialog.title" width="900px" :close-on-click-modal="false">
      <el-form ref="schemeFormRef" :model="schemeForm" :rules="schemeRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="方案日期" prop="expDate">
              <el-date-picker v-model="schemeForm.expDate" type="date" placeholder="选择方案日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供水量(M³)" prop="supplyTotal">
              <el-input-number v-model="schemeForm.supplyTotal" :min="0" :precision="0" controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="方案简述" prop="title">
          <el-input v-model="schemeForm.title" type="textarea" :rows="3" placeholder="请输入调度方案简述" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="平均压力(MPa)" prop="pressureAvg">
              <el-input-number v-model="schemeForm.pressureAvg" :min="0" :precision="2" :step="0.1"
                controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度评分" prop="ratingStar">
              <el-rate v-model="schemeForm.ratingStar" :max="5" show-text :texts="['很差', '差', '一般', '好', '很好']" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 机泵运行记录 -->
        <el-card class="mt-2">
          <template #header>
            <div class="card-header-with-button">
              <span>机泵运行记录</span>
              <el-button type="primary" size="small" @click="addRecord">添加记录</el-button>
            </div>
          </template>

          <div v-for="(record, index) in schemeForm.records" :key="index" class="record-item">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item :label="`开始时间`" :prop="`records[${index}].timeStart`" :rules="recordRules.timeStart">
                  <el-time-picker v-model="record.timeStart" placeholder="开始时间" format="HH:mm:ss"
                    value-format="HH:mm:ss" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="结束时间" :prop="`records[${index}].timeEnd`" :rules="recordRules.timeEnd">
                  <el-time-picker v-model="record.timeEnd" placeholder="结束时间" format="HH:mm:ss" value-format="HH:mm:ss"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="流量(m³/h)" :prop="`records[${index}].flowM3h`" :rules="recordRules.flowM3h">
                  <el-input-number v-model="record.flowM3h" :min="0" :precision="2" controls-position="right"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="压力(MPa)" :prop="`records[${index}].pressureMpa`" :rules="recordRules.pressureMpa">
                  <el-input-number v-model="record.pressureMpa" :min="0" :precision="2" :step="0.1"
                    controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="功率(kW)" :prop="`records[${index}].powerKw`" :rules="recordRules.powerKw">
                  <el-input-number v-model="record.powerKw" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button type="danger" text @click="removeRecord(index)" :disabled="schemeForm.records.length <= 1">
                  删除
                </el-button>
              </el-col>
            </el-row>
            <!-- 修改为下拉列表选择机泵状态 -->
            <el-form-item label="机泵状态配置">
              <div class="pump-config-container">
                <div v-for="pump in pumpList" :key="pump.id" class="pump-config-item">
                  <span class="pump-label">{{ pump.name }}：</span>
                  <el-select v-model="record.pumpStates[pump.id]" placeholder="选择状态" style="width: 120px;"
                    @change="updatePumpStatusJson(record)">
                    <el-option v-for="state in pumpStatusOptions" :key="state.value" :label="state.label"
                      :value="state.value" />
                  </el-select>
                </div>
              </div>
              <div class="pump-status-preview" v-if="record.pumpStatusJson">
                <span class="preview-label">状态预览：</span>
                <el-tag v-for="pump in parsePumpStatus(record.pumpStatusJson)" :key="pump.name"
                  :type="getPumpStatusType(pump.state)" size="small" class="preview-tag">
                  {{ pump.name }}:{{ pump.state }}
                </el-tag>
              </div>
            </el-form-item>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <el-button @click="schemeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitSchemeForm" :loading="schemeDialog.loading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, CopyDocument, Close } from '@element-plus/icons-vue'

// 导入图表组件
import ChartComponent from '@/components/ECharts'

// API接口
import {
  listDispatchScheduleExperience,
  getDispatchScheduleExperienceInfo,
  addDispatchScheduleExperience,
  removeDispatchScheduleExperience,
  addToLibraryDispatchScheduleExperience
} from '@/api/dispatch/affair/dispatch_exper'

// 响应式数据
const loading = ref(false)
const currentScheme = ref(null)
const total = ref(0)
const schemeList = ref([])

// 机泵配置
const pumpList = ref([
  { id: 'pump1', name: '1号泵' },
  { id: 'pump2', name: '2号泵' },
  { id: 'pump3', name: '3号泵' }
])

// 机泵状态选项
const pumpStatusOptions = ref([
  { value: '停止', label: '停止' },
  { value: '运行', label: '运行' },
  { value: '备用', label: '备用' }
])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  expDate: '',
  title: '',
  ratingStar: undefined
})

// 对话框控制
const schemeDialog = reactive({
  visible: false,
  title: '新增调度方案',
  mode: 'add', // 'add' | 'copy'
  loading: false
})

// 表单数据
const schemeForm = reactive({
  expDate: '',
  title: '',
  supplyTotal: 0,
  pressureAvg: 0,
  ratingStar: 3,
  records: [
    {
      timeStart: '',
      timeEnd: '',
      flowM3h: 0,
      pressureMpa: 0,
      powerKw: 0,
      pumpStates: {
        pump1: '停止',
        pump2: '停止',
        pump3: '停止'
      },
      pumpStatusJson: ''
    }
  ]
})

const schemeFormRef = ref()

// 记录字段验证规则
const recordRules = reactive({
  timeStart: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  timeEnd: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  flowM3h: [
    { required: true, message: '请输入流量', trigger: 'blur' },
    { type: 'number', min: 0, message: '流量不能为负数' }
  ],
  pressureMpa: [
    { required: true, message: '请输入压力', trigger: 'blur' },
    { type: 'number', min: 0, message: '压力不能为负数' }
  ],
  powerKw: [
    { required: true, message: '请输入功率', trigger: 'blur' },
    { type: 'number', min: 0, message: '功率不能为负数' }
  ]
})

// 表单验证规则
const schemeRules = reactive({
  expDate: [
    { required: true, message: '请选择方案日期', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入方案简述', trigger: 'blur' }
  ],
  supplyTotal: [
    { required: true, message: '请输入供水量', trigger: 'blur' },
    { type: 'number', min: 0, message: '供水量不能为负数' }
  ],
  pressureAvg: [
    { required: true, message: '请输入平均压力', trigger: 'blur' },
    { type: 'number', min: 0, message: '平均压力不能为负数' }
  ],
  ratingStar: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ]
})

// 图表配置计算属性
const flowChartOption = computed(() => {
  if (!currentScheme.value || !currentScheme.value.records) {
    return {}
  }

  const records = currentScheme.value.records
  const timeLabels = records.map(record => `${record.timeStart}-${record.timeEnd}`)
  const flowData = records.map(record => record.flowM3h || 0)

  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: timeLabels,
    },
    yAxis: {
      type: 'value',
      name: 'm³/h'
    },
    series: [{
      data: flowData,
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  }
})

const pressureChartOption = computed(() => {
  if (!currentScheme.value || !currentScheme.value.records) {
    return {}
  }

  const records = currentScheme.value.records
  const timeLabels = records.map(record => `${record.timeStart}-${record.timeEnd}`)
  const pressureData = records.map(record => record.pressureMpa || 0)

  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: timeLabels,
    },
    yAxis: {
      type: 'value',
      name: 'MPa'
    },
    series: [{
      data: pressureData,
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#67C23A'
      },
      lineStyle: {
        width: 3
      }
    }]
  }
})

const effectAnalysisChartOption = computed(() => {
  if (!currentScheme.value || !currentScheme.value.records) {
    return {}
  }

  const records = currentScheme.value.records
  const timeLabels = records.map(record => `${record.timeStart}-${record.timeEnd}`)
  const flowData = records.map(record => record.flowM3h || 0)
  const pressureData = records.map(record => record.pressureMpa || 0)
  const powerData = records.map(record => record.powerKw || 0)

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['流量(m³/h)', '压力(MPa)', '功率(kW)']
    },
    xAxis: {
      type: 'category',
      data: timeLabels,
    },
    yAxis: [
      {
        type: 'value',
        name: '流量/功率',
        position: 'left'
      },
      {
        type: 'value',
        name: '压力',
        position: 'right'
      }
    ],
    series: [
      {
        name: '流量(m³/h)',
        type: 'line',
        smooth: true,
        data: flowData,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '压力(MPa)',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: pressureData,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '功率(kW)',
        type: 'line',
        smooth: true,
        data: powerData,
        itemStyle: { color: '#E6A23C' }
      }
    ]
  }
})

// 初始化加载数据
onMounted(() => {
  loadSchemeList()
})

// 加载调度方案列表
const loadSchemeList = async () => {
  try {
    loading.value = true
    const res = await listDispatchScheduleExperience(queryParams)
    schemeList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取调度方案列表失败:', error)
    ElMessage.error('获取调度方案列表失败')
  } finally {
    loading.value = false
  }
}

// 获取调度方案详情
const loadSchemeDetail = async (id) => {
  try {
    const res = await getDispatchScheduleExperienceInfo(id)
    return res.data
  } catch (error) {
    console.error('获取调度方案详情失败:', error)
    throw error
  }
}

// 格式化数字
const formatNumber = (num) => {
  return num?.toLocaleString() || '0'
}

// 解析机泵状态JSON
const parsePumpStatus = (jsonStr) => {
  if (!jsonStr) return []
  try {
    return JSON.parse(jsonStr)
  } catch {
    return []
  }
}

// 获取机泵状态标签类型
const getPumpStatusType = (status) => {
  const types = {
    '运行': 'success',
    '停止': 'info',
    '备用': 'warning',
    '故障': 'danger'
  }
  return types[status] || 'info'
}

// 更新机泵状态JSON
const updatePumpStatusJson = (record) => {
  const pumpStatusArray = []
  pumpList.value.forEach(pump => {
    if (record.pumpStates[pump.id]) {
      pumpStatusArray.push({
        name: pump.name,
        state: record.pumpStates[pump.id]
      })
    }
  })
  record.pumpStatusJson = JSON.stringify(pumpStatusArray)
}

// 查看详情
const handleViewDetail = async (scheme) => {
  try {
    const detail = await loadSchemeDetail(scheme.id)
    currentScheme.value = detail
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 删除方案
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除调度方案 "${row.expDate}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return removeDispatchScheduleExperience(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    loadSchemeList()
  }).catch(() => { })
}

// 复制方案
const handleCopy = (scheme) => {
  schemeDialog.mode = 'copy'
  schemeDialog.title = '复制调度方案'
  schemeDialog.visible = true

  resetSchemeForm()
  schemeForm.expDate = ''
  schemeForm.title = scheme.title || ''
  schemeForm.supplyTotal = scheme.supplyTotal || 0
  schemeForm.pressureAvg = scheme.pressureAvg || 0
  schemeForm.ratingStar = scheme.ratingStar || 3

  // 处理记录数据
  if (scheme.records && scheme.records.length > 0) {
    schemeForm.records = scheme.records.map(record => {
      const pumpStates = { pump1: '停止', pump2: '停止', pump3: '停止' }

      if (record.pumpStatusJson) {
        try {
          const statusArray = JSON.parse(record.pumpStatusJson)
          statusArray.forEach(item => {
            const pumpKey = pumpList.value.find(p => p.name === item.name)?.id
            if (pumpKey) {
              pumpStates[pumpKey] = item.state
            }
          })
        } catch (e) {
          console.error('解析机泵状态JSON失败:', e)
        }
      }

      return {
        timeStart: record.timeStart || '',
        timeEnd: record.timeEnd || '',
        flowM3h: record.flowM3h || 0,
        pressureMpa: record.pressureMpa || 0,
        powerKw: record.powerKw || 0,
        pumpStates: pumpStates,
        pumpStatusJson: record.pumpStatusJson || ''
      }
    })
  }
}

// 保存方案
const handleSave = async (scheme) => {
  try {
    await ElMessageBox.confirm(`确定保存调度方案 "${scheme.expDate}" 吗？`, '提示', {
      type: 'warning'
    })
    await addToLibraryDispatchScheduleExperience(scheme.id)
    ElMessage.success('保存成功')
  } catch {
    // 用户取消
  }
}

// 添加方案库
const handleAddToLibrary = () => {
  schemeDialog.mode = 'add'
  schemeDialog.title = '新增调度方案'
  schemeDialog.visible = true
  resetSchemeForm()
}

// 复制方案按钮
const handleCopyScheme = () => {
  if (!currentScheme.value) {
    ElMessage.warning('请先选择一个方案进行复制')
    return
  }
  handleCopy(currentScheme.value)
}

// 保存到方案库
const handleSaveToLibrary = async () => {
  if (!currentScheme.value) return

  try {
    await ElMessageBox.confirm(`确定将方案保存到方案库吗？`, '提示', {
      type: 'warning'
    })

    await addToLibraryDispatchScheduleExperience(currentScheme.value.id)
    ElMessage.success('保存到方案库成功')
    loadSchemeList()
  } catch {
    // 用户取消
  }
}

// 复制到未来
const handleCopyToFuture = () => {
  if (!currentScheme.value) return
  handleCopy(currentScheme.value)
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  loadSchemeList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  loadSchemeList()
}

// 重置表单
const resetSchemeForm = () => {
  schemeForm.expDate = ''
  schemeForm.title = ''
  schemeForm.supplyTotal = 0
  schemeForm.pressureAvg = 0
  schemeForm.ratingStar = 3
  schemeForm.records = [
    {
      timeStart: '',
      timeEnd: '',
      flowM3h: 0,
      pressureMpa: 0,
      powerKw: 0,
      pumpStates: {
        pump1: '停止',
        pump2: '停止',
        pump3: '停止'
      },
      pumpStatusJson: ''
    }
  ]
}

// 添加记录
const addRecord = () => {
  schemeForm.records.push({
    timeStart: '',
    timeEnd: '',
    flowM3h: 0,
    pressureMpa: 0,
    powerKw: 0,
    pumpStates: {
      pump1: '停止',
      pump2: '停止',
      pump3: '停止'
    },
    pumpStatusJson: ''
  })
}

// 删除记录
const removeRecord = (index) => {
  if (schemeForm.records.length > 1) {
    schemeForm.records.splice(index, 1)
  }
}

// 提交表单
const submitSchemeForm = async () => {
  try {
    if (!schemeFormRef.value) return

    // 确保所有记录的pumpStatusJson都是最新的
    schemeForm.records.forEach(record => {
      updatePumpStatusJson(record)
    })

    await schemeFormRef.value.validate()

    schemeDialog.loading = true

    if (schemeDialog.mode === 'add') {
      await addDispatchScheduleExperience(schemeForm)
      ElMessage.success('新增成功')
    } else {
      await addDispatchScheduleExperience(schemeForm)
      ElMessage.success('复制成功')
    }

    schemeDialog.visible = false
    loadSchemeList()
  } catch (error) {
    console.error('保存失败:', error)
    if (error && error.fields) {
      ElMessage.warning('请检查表单填写是否正确')
      return
    }
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    schemeDialog.loading = false
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.header-buttons,
.detail-buttons {
  display: flex;
  gap: 10px;
}

.mt-2 {
  margin-top: 20px;
}

.mt-1 {
  margin-top: 10px;
}

.detail-content {
  padding: 0;
}

.basic-info {
  background: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
}

.info-item span {
  color: #303133;
}

.pump-status {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.pump-status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pump-name {
  font-size: 12px;
  color: #606266;
  min-width: 60px;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

.card-header-with-button {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-item {
  width: 100%;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 16px;
  background: #f8f9fa;
}

.record-item:last-child {
  margin-bottom: 0;
}

.unit {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

/* 机泵配置样式 */
.pump-config-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.pump-config-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pump-label {
  font-size: 14px;
  color: #606266;
  min-width: 60px;
}

.pump-status-preview {
  margin-top: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.preview-label {
  font-size: 12px;
  color: #909399;
  margin-right: 8px;
}

.preview-tag {
  margin-right: 6px;
  margin-bottom: 4px;
}

/* 修复样式选择器问题 */
:deep(.el-card__header) {
  padding: 16px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-rate) {
  display: inline-flex;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .header-buttons,
  .detail-buttons {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .basic-info .el-col {
    margin-bottom: 16px;
  }

  .record-item .el-col {
    margin-bottom: 12px;
  }

  .pump-config-container {
    flex-direction: column;
    gap: 12px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table .cell) {
    padding: 4px 8px;
  }
}
</style>